
//               File: ProductDataAdapter
//        Description: Product
//             Author: DeKlarit - Language C# - Generator Version 10_1_3-31907 - Specifier Version 10_1_3.31907
//       Program type: Deklarit Business Component
//          Main DBMS: Microsoft SqlServer

namespace DeklaritModel {
   using System;
   using System.Collections;
   using Deklarit.Utils;
   using System.Data;
   using System.Data.SqlClient;
   using System.Data.Common;
   using Deklarit.Data;
   using System.ComponentModel.Design;
   using System.Runtime.Serialization;
   using System.Security.Permissions;
   using System.Data.SqlTypes;
   public partial class ProductDataAdapter : System.Data.IDataAdapter, IProductDataAdapter
   {
      private ProductDataSet ProductSet ;
      private IDbTransaction daCurrentTransaction ;
      private ProductDataSet.ProductRow rowProduct ;
      public ProductDataAdapter( )
      {
      }

      private void InitializeMembers( )
      {
         ProductSet = new ProductDataSet() ;
         this.Initialize( ) ;
         dsDefault = new DataStore( new SqlServer2005Handler( ), "System.Data.SqlClient", DeklaritModel.Configuration.ConnectionString, DeklaritTransaction.TransactionSlotName) ;
      }

      ///  <summary>
      ///   Gets or sets the Transaction object to be used  by  ProductDataAdapterclasses to
      ///    commit changes to the Database.
      ///  </summary>
      public IDbTransaction Transaction
      {
         get {
            return daCurrentTransaction ;
         }

         set {
            daCurrentTransaction = value ;
         }

      }

      ///  <summary>
      ///   Gets or sets the missing mapping action.
      ///  </summary>
      public MissingMappingAction MissingMappingAction
      {
         get {
            return System.Data.MissingMappingAction.Passthrough ;
         }

         set {
         }

      }

      ///  <summary>
      ///   Gets or sets the missing schema action.
      ///  </summary>
      public MissingSchemaAction MissingSchemaAction
      {
         get {
            return System.Data.MissingSchemaAction.Ignore ;
         }

         set {
         }

      }

      ///  <summary>
      ///   Gets the table mappings.
      ///  </summary>
      public ITableMappingCollection TableMappings
      {
         get {
            System.Data.Common.DataTableMappingCollection tableMaps ;
            tableMaps = new System.Data.Common.DataTableMappingCollection() ;
            return tableMaps ;
         }

      }

      ///  <summary>
      ///   Fills the schema for the datasource.
      ///  </summary>
      ///  <param name="dataSet">DataSet</param>
      ///  <param name="schemaType">Schema type</param>
      public virtual DataTable[] FillSchema( DataSet dataSet ,
                                             SchemaType schemaType )
      {
         DataTable[] dataTables ;
         dataTables = new DataTable[dataSet.Tables.Count]  ;
         dataSet.Tables.CopyTo( dataTables, dataSet.Tables.Count) ;
         return dataTables ;
      }


      ///  <summary>
      ///   (2) Fills the specified Dataset with the record matching ProductId field(s) of the
      ///    given IDataRecord
      ///  </summary>
      ///  <param name="dataSet">DataSet</param>
      ///  <param name="dataRecord">Data Record</param>
      public virtual int Fill( ProductDataSet dataSet ,
                               IDataRecord dataRecord )
      {
         return Fill(dataSet, ((short)(dataRecord["ProductId"]))) ;
      }

      ///  <summary>
      ///   (3) Fills the specified Dataset with the record matching ProductId field(s) of the
      ///    given DataRow
      ///  </summary>
      ///  <param name="dataSet">DataSet</param>
      ///  <param name="dataRecord">Data Row</param>
      public virtual int Fill( ProductDataSet dataSet ,
                               DataRow dataRecord )
      {
         return Fill(dataSet, ((short)(dataRecord["ProductId"]))) ;
      }

      ///  <summary>
      ///   (4) Fills the specified Dataset with the record matching ProductId, if the record
      ///    is not found , throws an exception.
      ///  </summary>
      ///  <param name="dataSet">DataSet</param>
      ///  <param name="productId">Id</param>
      public virtual int Fill( ProductDataSet dataSet ,
                               short productId )
      {
         if ( ! FillByProductId( dataSet, productId) )
         {
            throw new ProductNotFoundException( string.Format(resourceManager.GetString("GXM_inex"), new   object[]  {"Product"})) ;
         }
         return 0 ;
      }


      ///  <summary>
      ///   (5) Fills the specified Dataset with the record matching ProductId in the fillDataParameters
      ///    array, if the array is null, it fills the Dataset loading all records in the table.
      ///
      ///  </summary>
      ///  <param name="dataSet">DataSet</param>
      public virtual int Fill( ProductDataSet dataSet )
      {
         if ( fillDataParameters != null )
         {
            Fill( dataSet, System.Int16.Parse( fillDataParameters[0].Value.ToString())) ;
         }
         else
         {
            try
            {
               InitializeMembers( ) ;
               connDefault = dsDefault.GetReadWriteConnection( daCurrentTransaction) ;
               ProductSet = dataSet ;
               LoadChildProduct( 0, -1) ;
               dataSet.AcceptChanges( ) ;
            }
            finally
            {
               this.Cleanup();
            }
         }
         return 0 ;
      }


      ///  <summary>
      ///   (6) Fills the specified dataset filtered by ProductIdfield(s).
      ///  </summary>
      ///  <param name="dataSet">DataSet</param>
      ///  <param name="productId">Id</param>
      public virtual bool FillByProductId( ProductDataSet dataSet ,
                                           short productId )
      {
         InitializeMembers( ) ;
         connDefault = dsDefault.GetReadWriteConnection( daCurrentTransaction) ;
         ProductSet = dataSet ;
         rowProduct = ProductSet.Product.NewProductRow() ;
         rowProduct.ProductId = productId ;
         try
         {
            LoadByProductId( 0, -1) ;
            dataSet.AcceptChanges( ) ;
         }
         finally
         {
            this.Cleanup();
         }
         if ( RcdFound4 == 0 )
         {
            return false ;
         }
         return true ;
      }


      ///  <summary>
      ///   (8) Fills the specified dataset with the record matching ProductId in the the fillDataParameters
      ///    array, if the array is null, it fills the Dataset loading all records in the table.
      ///
      ///  </summary>
      ///  <param name="dataSet">DataSet</param>
      public virtual int Fill( DataSet dataSet )
      {
         ProductSet = dataSet as ProductDataSet ;
         if ( ProductSet != null )
         {
            return Fill( ProductSet) ;
         }
         else
         {
            ProductSet = new ProductDataSet() ;
            Fill( ProductSet) ;
            dataSet.Merge( ProductSet) ;
            return 0 ;
         }
      }

      ///  <summary>
      ///   (11) Fills a page of up to maxRows rows into the specified dataset starting at startRow
      ///
      ///  </summary>
      ///  <param name="dataSet">DataSet</param>
      ///  <param name="startRow">Starting row</param>
      ///  <param name="maxRows">Max number of rows to load</param>
      public virtual int FillPage( ProductDataSet dataSet ,
                                   int startRow ,
                                   int maxRows )
      {
         InitializeMembers( ) ;
         connDefault = dsDefault.GetReadWriteConnection( daCurrentTransaction) ;
         ProductSet = dataSet ;
         try
         {
            LoadChildProduct( startRow, maxRows) ;
            dataSet.AcceptChanges( ) ;
         }
         finally
         {
            this.Cleanup();
         }
         return 0 ;
      }


      ///  <summary>
      ///   (9) Gets the total record count.
      ///  </summary>
      public virtual int GetRecordCount( )
      {
         int m_Count ;
         try
         {
            InitializeMembers( ) ;
            m_Count = GetInternalRecordCount(  ) ;
         }
         finally
         {
            this.Cleanup();
         }
         return m_Count ;
      }

      private int GetInternalRecordCount( )
      {
         connDefault = dsDefault.GetReadWriteConnection( daCurrentTransaction) ;
         cmPRODUCTSELECT1 = connDefault.GetCommand("SELECT COUNT(*) FROM [Product] WITH (NOLOCK) ", false) ;
         PRODUCTSELECT1 = cmPRODUCTSELECT1.FetchData() ;
         recordCount = ( ( PRODUCTSELECT1.IsDBNull(0) )  ? (int)(0) : PRODUCTSELECT1.GetInt32(0) ) ;
         PRODUCTSELECT1.Close();
         return recordCount ;
      }

      ///  <summary>
      ///   Gets the fill parameters array.
      ///  </summary>
      public virtual IDataParameter[] GetFillParameters( )
      {
         if ( fillDataParameters == null )
         {
            DbProviderFactory factory = System.Data.Common.DbProviderFactories.GetFactory( "System.Data.SqlClient") ;
            DbParameter parm0ProductId ;
            parm0ProductId = factory.CreateParameter() ;
            parm0ProductId.ParameterName = "ProductId" ;
            parm0ProductId.DbType = System.Data.DbType.Int16 ;
            fillDataParameters = new  DbParameter[]  {parm0ProductId} ;
         }
         return fillDataParameters ;
      }

      private DbParameter[] fillDataParameters ;

      ///  <summary>
      ///   Inserts, Updates or Deletes records from the specified ProductDataSet object.
      ///  </summary>
      ///  <param name="dataSet">DataSet</param>
      public virtual int Update( DataSet dataSet )
      {
         InitializeMembers( ) ;
         ProductSet = dataSet as ProductDataSet ;
         connDefault = dsDefault.GetReadWriteConnection( daCurrentTransaction) ;
         if ( ProductSet != null )
         {
            try
            {
               connDefault.BeginTransaction();
               foreach( ProductDataSet.ProductRow row in ProductSet.Product )
               {
                  rowProduct = row ;
                  if ( Deklarit.Data.Helpers.IsRowChanged(rowProduct) )
                  {
                     ReadRowProduct( ) ;
                     if ( rowProduct.RowState == System.Data.DataRowState.Added )
                     {
                        InsertProduct( ) ;
                     }
                     else
                     {
                        if ( _Gxremove )
                        {
                           Delete( ) ;
                        }
                        else
                        {
                           UpdateProduct( ) ;
                        }
                     }
                  }
               }

               dataSet.AcceptChanges( ) ;
               connDefault.Commit();
            }
            catch ( Exception  )
            {
               connDefault.Rollback();
               throw  ;
            }
            finally
            {
               this.Cleanup();
            }
         }
         else
         {
            throw new System.ArgumentException( string.Format(resourceManager.GetString("GXM_nulldset"), new   object[]  {})) ;
         }
         return 0 ;
      }

      private void LoadRowProduct( )
      {
         AddRowProduct( ) ;
      }

      private void ReadRowProduct( )
      {
         Gx_mode = Deklarit.Utils.Mode.FromRowState(rowProduct.RowState) ;
         if ( rowProduct.RowState != System.Data.DataRowState.Added )
         {
            m__ProductNameOriginal = rowProduct["ProductName", System.Data.DataRowVersion.Original] ;
            m__ProductTypeOriginal = rowProduct["ProductType", System.Data.DataRowVersion.Original] ;
            m__ProductSizeOriginal = rowProduct["ProductSize", System.Data.DataRowVersion.Original] ;
            m__ProductIsFragileOriginal = rowProduct["ProductIsFragile", System.Data.DataRowVersion.Original] ;
            m__ProductClassOriginal = rowProduct["ProductClass", System.Data.DataRowVersion.Original] ;
         }
         else
         {
            m__ProductNameOriginal = rowProduct["ProductName"] ;
            m__ProductTypeOriginal = rowProduct["ProductType"] ;
            m__ProductSizeOriginal = rowProduct["ProductSize"] ;
            m__ProductIsFragileOriginal = rowProduct["ProductIsFragile"] ;
            m__ProductClassOriginal = rowProduct["ProductClass"] ;
         }
         _Gxremove = (bool)((rowProduct.RowState==System.Data.DataRowState.Deleted)) ;
         if ( _Gxremove )
         {
            rowProduct = ((ProductDataSet.ProductRow)(Deklarit.Utils.DataSetUtil.CloneOriginalDataRow(rowProduct)));
         }
      }

      private void CheckExtendedTableProduct( )
      {
         if ( !  System.Enum.IsDefined(typeof(ProductClass),((int)(((short)(rowProduct["ProductClass"]))))) )
         {
            throw new ProductClassInvalidValue( "Invalid Clase Value") ;
         }
      }

      private void GetByPrimaryKey( )
      {
          IDataReader PRODUCTSELECT2 ;
          ReadWriteCommand cmPRODUCTSELECT2 ;
         cmPRODUCTSELECT2 = connDefault.GetCommand("SELECT [ProductId], [ProductName], [ProductType], [ProductSize], [ProductIsFragile], [ProductClass] FROM [Product] WITH (NOLOCK) WHERE [ProductId] = @ProductId ", false) ;
         if ( cmPRODUCTSELECT2.IDbCommand.Parameters.Count == 0 )
         {
            cmPRODUCTSELECT2.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductId", System.Data.DbType.Int16));
         }
         cmPRODUCTSELECT2.SetParameter(0, rowProduct["ProductId"]);
         PRODUCTSELECT2 = cmPRODUCTSELECT2.FetchData() ;
         if ( cmPRODUCTSELECT2.HasMoreRows )
         {
            RcdFound4 = 1 ;
            rowProduct["ProductId"] = dsDefault.Db.GetInt16(PRODUCTSELECT2, 0) ;
            rowProduct["ProductName"] = dsDefault.Db.GetString(PRODUCTSELECT2, 1) ;
            rowProduct["ProductType"] = dsDefault.Db.GetString(PRODUCTSELECT2, 2) ;
            rowProduct["ProductSize"] = dsDefault.Db.GetInt16(PRODUCTSELECT2, 3) ;
            rowProduct["ProductIsFragile"] = dsDefault.Db.GetBoolean(PRODUCTSELECT2, 4) ;
            rowProduct["ProductClass"] = dsDefault.Db.GetInt16(PRODUCTSELECT2, 5) ;
            sMode4 = Gx_mode ;
            Gx_mode = Mode.Display ;
            Gx_mode = sMode4 ;
         }
         else
         {
            RcdFound4 = 0 ;
         }
         PRODUCTSELECT2.Close();
      }

      private void CheckOptimisticConcurrencyProduct( )
      {
          ReadWriteCommand cmPRODUCTSELECT3 ;
         if ( Gx_mode != Mode.Insert )
         {
            cmPRODUCTSELECT3 = connDefault.GetCommand("SELECT [ProductId], [ProductName], [ProductType], [ProductSize], [ProductIsFragile], [ProductClass] FROM [Product] WITH (UPDLOCK) WHERE [ProductId] = @ProductId ", false) ;
            if ( cmPRODUCTSELECT3.IDbCommand.Parameters.Count == 0 )
            {
               cmPRODUCTSELECT3.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductId", System.Data.DbType.Int16));
            }
            cmPRODUCTSELECT3.SetParameter(0, rowProduct["ProductId"]);
            PRODUCTSELECT3 = cmPRODUCTSELECT3.FetchData() ;
            if ( cmPRODUCTSELECT3.Locked )
            {
               PRODUCTSELECT3.Close();
               throw new ProductDataLockedException( string.Format(resourceManager.GetString("GXM_lock"), new   object[]  {"Product"})) ;
            }
            if ( !cmPRODUCTSELECT3.HasMoreRows || ( ! StringUtil.ObjectStringEquals(m__ProductNameOriginal,dsDefault.Db.GetString(PRODUCTSELECT3, 1)) ) || ( ! StringUtil.ObjectStringEquals(m__ProductTypeOriginal,dsDefault.Db.GetString(PRODUCTSELECT3, 2)) ) || ( ! m__ProductSizeOriginal.Equals(dsDefault.Db.GetInt16(PRODUCTSELECT3, 3)) ) || ( ! m__ProductIsFragileOriginal.Equals(dsDefault.Db.GetBoolean(PRODUCTSELECT3, 4)) ) || ( ! m__ProductClassOriginal.Equals(dsDefault.Db.GetInt16(PRODUCTSELECT3, 5)) ) )
            {
               PRODUCTSELECT3.Close();
               throw new ProductDataChangedException( string.Format(resourceManager.GetString("GXM_waschg"), new   object[]  {"Product"})) ;
            }
            PRODUCTSELECT3.Close();
         }
      }

      private void InsertProduct( )
      {
          IDataReader PRODUCTINSERT1 ;
          ReadWriteCommand cmPRODUCTINSERT1 ;
         CheckExtendedTableProduct( ) ;
         CheckOptimisticConcurrencyProduct( ) ;
         AfterConfirmProduct( ) ;
         cmPRODUCTINSERT1 = connDefault.GetCommand("INSERT INTO [Product] ([ProductName], [ProductType], [ProductSize], [ProductIsFragile], [ProductClass]) VALUES (@ProductName, @ProductType, @ProductSize, @ProductIsFragile, @ProductClass); SELECT SCOPE_IDENTITY()", false) ;
         if ( cmPRODUCTINSERT1.IDbCommand.Parameters.Count == 0 )
         {
            cmPRODUCTINSERT1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductName", System.Data.DbType.AnsiStringFixedLength,20));
            cmPRODUCTINSERT1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductType", System.Data.DbType.AnsiStringFixedLength,20));
            cmPRODUCTINSERT1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductSize", System.Data.DbType.Int16));
            cmPRODUCTINSERT1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductIsFragile", System.Data.DbType.Boolean));
            cmPRODUCTINSERT1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductClass", System.Data.DbType.Int16));
         }
         cmPRODUCTINSERT1.ErrorMask = cmPRODUCTINSERT1.ErrorMask  |  ErrorMask.DuplicateKeyError;
         cmPRODUCTINSERT1.SetParameter(0, rowProduct["ProductName"]);
         cmPRODUCTINSERT1.SetParameter(1, rowProduct["ProductType"]);
         cmPRODUCTINSERT1.SetParameter(2, rowProduct["ProductSize"]);
         cmPRODUCTINSERT1.SetParameter(3, rowProduct["ProductIsFragile"]);
         cmPRODUCTINSERT1.SetParameter(4, rowProduct["ProductClass"]);
         PRODUCTINSERT1 = cmPRODUCTINSERT1.FetchData() ;
         rowProduct.ProductId = (short)(PRODUCTINSERT1.GetDecimal(0)) ;
         PRODUCTINSERT1.Close();
         // Start of After( Insert) rules
         // End of After( Insert) rules
         OnProductUpdated( new ProductEventArgs( rowProduct, Mode.Insert)) ;
         // Save values for previous() function.
         EndLevelProduct( ) ;
      }

      private void UpdateProduct( )
      {
          ReadWriteCommand cmPRODUCTUPDATE1 ;
         CheckExtendedTableProduct( ) ;
         CheckOptimisticConcurrencyProduct( ) ;
         AfterConfirmProduct( ) ;
         cmPRODUCTUPDATE1 = connDefault.GetCommand("UPDATE [Product] SET [ProductName]=@ProductName, [ProductType]=@ProductType, [ProductSize]=@ProductSize, [ProductIsFragile]=@ProductIsFragile, [ProductClass]=@ProductClass  WHERE [ProductId] = @ProductId", false) ;
         if ( cmPRODUCTUPDATE1.IDbCommand.Parameters.Count == 0 )
         {
            cmPRODUCTUPDATE1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductName", System.Data.DbType.AnsiStringFixedLength,20));
            cmPRODUCTUPDATE1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductType", System.Data.DbType.AnsiStringFixedLength,20));
            cmPRODUCTUPDATE1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductSize", System.Data.DbType.Int16));
            cmPRODUCTUPDATE1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductIsFragile", System.Data.DbType.Boolean));
            cmPRODUCTUPDATE1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductClass", System.Data.DbType.Int16));
            cmPRODUCTUPDATE1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductId", System.Data.DbType.Int16));
         }
         // Using cursor PRODUCTUPDATE1
         cmPRODUCTUPDATE1.SetParameter(0, rowProduct["ProductName"]);
         cmPRODUCTUPDATE1.SetParameter(1, rowProduct["ProductType"]);
         cmPRODUCTUPDATE1.SetParameter(2, rowProduct["ProductSize"]);
         cmPRODUCTUPDATE1.SetParameter(3, rowProduct["ProductIsFragile"]);
         cmPRODUCTUPDATE1.SetParameter(4, rowProduct["ProductClass"]);
         cmPRODUCTUPDATE1.SetParameter(5, rowProduct["ProductId"]);
         cmPRODUCTUPDATE1.ExecuteStmt();
         if ( cmPRODUCTUPDATE1.Locked )
         {
            PRODUCTSELECT3.Close();
            throw new ProductDataLockedException( string.Format(resourceManager.GetString("GXM_lock"), new   object[]  {"Product"})) ;
         }
         // Start of After( update) rules
         // End of After( update) rules
         OnProductUpdated( new ProductEventArgs( rowProduct, Mode.Update)) ;
         EndLevelProduct( ) ;
      }

      private void Delete( )
      {
          ReadWriteCommand cmPRODUCTDELETE1 ;
         Gx_mode = Mode.Delete ;
         CheckOptimisticConcurrencyProduct( ) ;
         AfterConfirmProduct( ) ;
         // No cascading delete specified.
         cmPRODUCTDELETE1 = connDefault.GetCommand("DELETE FROM [Product]  WHERE [ProductId] = @ProductId", false) ;
         if ( cmPRODUCTDELETE1.IDbCommand.Parameters.Count == 0 )
         {
            cmPRODUCTDELETE1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductId", System.Data.DbType.Int16));
         }
         cmPRODUCTDELETE1.ErrorMask = cmPRODUCTDELETE1.ErrorMask  |  ErrorMask.ForeignKeyError;
         // Using cursor PRODUCTDELETE1
         cmPRODUCTDELETE1.SetParameter(0, rowProduct["ProductId"]);
         cmPRODUCTDELETE1.ExecuteStmt();
         if ( cmPRODUCTDELETE1.ForeignKeyError )
         {
            CheckDeleteErrorsProduct( ) ;
         }
         // Start of After( delete) rules
         // End of After( delete) rules
         OnProductUpdated( new ProductEventArgs( rowProduct, Mode.Delete)) ;
         rowProduct.Delete( ) ;
         sMode4 = Gx_mode ;
         Gx_mode = Mode.Delete ;
         EndLevelProduct( ) ;
         Gx_mode = sMode4 ;
      }

      private void CheckDeleteErrorsProduct( )
      {
          IDataReader INVOICELINESELECT1 ;
          ReadWriteCommand cmINVOICELINESELECT1 ;
         cmINVOICELINESELECT1 = connDefault.GetCommand("SELECT TOP 1 [InvoiceId], [InvoiceLineId] FROM [InvoiceLine] WITH (NOLOCK) WHERE [ProductId] = @ProductId ", false) ;
         if ( cmINVOICELINESELECT1.IDbCommand.Parameters.Count == 0 )
         {
            cmINVOICELINESELECT1.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductId", System.Data.DbType.Int16));
         }
         cmINVOICELINESELECT1.SetParameter(0, rowProduct["ProductId"]);
         INVOICELINESELECT1 = cmINVOICELINESELECT1.FetchData() ;
         if ( cmINVOICELINESELECT1.HasMoreRows )
         {
            INVOICELINESELECT1.Close();
            throw new InvoiceLineInvalidDeleteException( string.Format(resourceManager.GetString("GXM_del"), new   object[]  {"Line"})) ;
         }
         INVOICELINESELECT1.Close();
      }

      private void EndLevelProduct( )
      {
         // Execute 'After Trn' event if defined.
         IsModified = 0 ;
      }

      private void ScanByProductId( int startRow ,
                                    int maxRows )
      {
         m_WhereString = " WHERE TM1.[ProductId] = @ProductId" ;
         if ( maxRows >= 0 )
         {
            if ( startRow == 0 )
            {
               scmdbuf = "SELECT TOP " + maxRows.ToString() + "  " + m_SelectString4 + "  FROM [Product] TM1 WITH (NOLOCK)" + m_WhereString + " ORDER BY TM1.[ProductId]" ;
            }
            else
            {
               scmdbuf = " SELECT * FROM ( SELECT  " + m_SelectString4 + ", ROW_NUMBER() OVER  (  ORDER BY TM1.[ProductId] ) AS DK_PAGENUM   FROM [Product] TM1 WITH (NOLOCK) " + m_WhereString + " ) AS DK_PAGE WHERE DK_PAGENUM BETWEEN " + (startRow + 1).ToString() + " AND " + (startRow + maxRows).ToString() ;
            }
         }
         else
         {
            scmdbuf = "SELECT " + m_SelectString4 + " FROM [Product] TM1 WITH (NOLOCK)" + m_WhereString + " ORDER BY TM1.[ProductId] " ;
         }
         cmPRODUCTSELECT4 = connDefault.GetCommand(scmdbuf, false) ;
         if ( cmPRODUCTSELECT4.IDbCommand.Parameters.Count == 0 )
         {
            cmPRODUCTSELECT4.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductId", System.Data.DbType.Int16));
         }
         cmPRODUCTSELECT4.SetParameter(0, rowProduct["ProductId"]);
         PRODUCTSELECT4 = cmPRODUCTSELECT4.FetchData() ;
         RcdFound4 = 0 ;
         ScanKeyLoadProduct( ) ;
         LoadKeyDataProduct( maxRows) ;
         // Load Subordinate Levels
      }

      private void ScanKeyStartProduct( int startRow ,
                                        int maxRows )
      {
         m_WhereString = "" ;
         if ( maxRows >= 0 )
         {
            if ( startRow == 0 )
            {
               scmdbuf = "SELECT TOP " + maxRows.ToString() + "  " + m_SelectString4 + "  FROM [Product] TM1 WITH (NOLOCK)" + m_WhereString + " ORDER BY TM1.[ProductId]" ;
            }
            else
            {
               scmdbuf = " SELECT * FROM ( SELECT  " + m_SelectString4 + ", ROW_NUMBER() OVER  (  ORDER BY TM1.[ProductId] ) AS DK_PAGENUM   FROM [Product] TM1 WITH (NOLOCK) " + m_WhereString + " ) AS DK_PAGE WHERE DK_PAGENUM BETWEEN " + (startRow + 1).ToString() + " AND " + (startRow + maxRows).ToString() ;
            }
         }
         else
         {
            scmdbuf = "SELECT " + m_SelectString4 + " FROM [Product] TM1 WITH (NOLOCK)" + m_WhereString + " ORDER BY TM1.[ProductId] " ;
         }
         cmPRODUCTSELECT4 = connDefault.GetCommand(scmdbuf, false) ;
         PRODUCTSELECT4 = cmPRODUCTSELECT4.FetchData() ;
         RcdFound4 = 0 ;
         ScanKeyLoadProduct( ) ;
         LoadKeyDataProduct( maxRows) ;
         // Load Subordinate Levels
      }

      private void ScanKeyNextProduct( )
      {
         cmPRODUCTSELECT4.HasMoreRows = PRODUCTSELECT4.Read() ;
         RcdFound4 = 0 ;
         ScanKeyLoadProduct( ) ;
      }

      private void ScanKeyLoadProduct( )
      {
         sMode4 = Gx_mode ;
         Gx_mode = Mode.Display ;
         if ( cmPRODUCTSELECT4.HasMoreRows )
         {
            RcdFound4 = 1 ;
            rowProduct["ProductId"] = dsDefault.Db.GetInt16(PRODUCTSELECT4, 0) ;
            rowProduct["ProductName"] = dsDefault.Db.GetString(PRODUCTSELECT4, 1) ;
            rowProduct["ProductType"] = dsDefault.Db.GetString(PRODUCTSELECT4, 2) ;
            rowProduct["ProductSize"] = dsDefault.Db.GetInt16(PRODUCTSELECT4, 3) ;
            rowProduct["ProductIsFragile"] = dsDefault.Db.GetBoolean(PRODUCTSELECT4, 4) ;
            rowProduct["ProductClass"] = dsDefault.Db.GetInt16(PRODUCTSELECT4, 5) ;
         }
         Gx_mode = sMode4 ;
      }

      private void ScanKeyEndProduct( )
      {
         PRODUCTSELECT4.Close();
      }

      private void AfterConfirmProduct( )
      {
         // After Confirm Rules
         OnProductUpdating( new ProductEventArgs( rowProduct, Gx_mode)) ;
      }

      private void CreateNewRowProduct( )
      {
         rowProduct = ProductSet.Product.NewProductRow() ;
      }

      private void LoadChildProduct( int startRow ,
                                     int maxRows )
      {
         CreateNewRowProduct( ) ;
         bool tmpConstraintState = ProductSet.EnforceConstraints ;
         ProductSet.Product.BeginLoadData( ) ;
         ScanKeyStartProduct( startRow, maxRows) ;
         ProductSet.Product.EndLoadData( ) ;
         this.ProductSet.EnforceConstraints = tmpConstraintState ;
      }

      private void LoadKeyDataProduct( int maxRows )
      {
         int loadedRows = 0 ;
         if ( RcdFound4 != 0 )
         {
            ScanKeyLoadProduct( ) ;
            while ( ( RcdFound4 != 0 ) && ( loadedRows != maxRows ) )
            {
               loadedRows++ ;
               LoadRowProduct( ) ;
               CreateNewRowProduct( ) ;
               ScanKeyNextProduct( ) ;
            }
         }
         if ( loadedRows > 0 )
         {
            RcdFound4 = 1 ;
         }
         ScanKeyEndProduct( ) ;
         if ( ProductSet.Product.Count > 0 )
         {
            rowProduct = ProductSet.Product[ProductSet.Product.Count -1] ;
         }
      }

      private void LoadByProductId( int startRow ,
                                    int maxRows )
      {
         bool tmpConstraintState = ProductSet.EnforceConstraints ;
         ProductSet.Product.BeginLoadData( ) ;
         ScanByProductId( startRow, maxRows) ;
         ProductSet.Product.EndLoadData( ) ;
         this.ProductSet.EnforceConstraints = tmpConstraintState ;
         if ( ProductSet.Product.Count > 0 )
         {
            rowProduct = ProductSet.Product[ProductSet.Product.Count -1] ;
         }
      }

      private void AddRowProduct( )
      {
         ProductSet.Product.AddProductRow( rowProduct) ;
      }

      private readonly string m_SelectString4 = "TM1.[ProductId], TM1.[ProductName], TM1.[ProductType], TM1.[ProductSize], TM1.[ProductIsFragile], TM1.[ProductClass]" ;


      public delegate  void ProductUpdateEventHandler( object sender ,
                                                       ProductEventArgs e );
      public event ProductUpdateEventHandler ProductUpdated ;
      private void OnProductUpdated( ProductEventArgs e )
      {
         if ( this.ProductUpdated != null )
         {
            this.ProductUpdated( this, e) ;
         }
      }

      public event ProductUpdateEventHandler ProductUpdating ;
      private void OnProductUpdating( ProductEventArgs e )
      {
         if ( this.ProductUpdating != null )
         {
            this.ProductUpdating( this, e) ;
         }
      }

      public class ProductEventArgs : EventArgs
      {
         private System.Data.StatementType m_statementType ;
         private ProductDataSet.ProductRow m_dataRow ;
         public ProductEventArgs( ProductDataSet.ProductRow row ,
                                  StatementType statementType )
         {
            m_dataRow = row ;
            m_statementType = statementType ;
         }

         public System.Data.StatementType StatementType
         {
            get {
               return m_statementType ;
            }

         }

         public ProductDataSet.ProductRow Row
         {
            get {
               return m_dataRow ;
            }

            set {
               m_dataRow = value ;
            }

         }

      }


      // Custom Exceptions
      [Serializable()]
      public class ProductNotFoundException : Deklarit.DataNotFoundException
      {
         public ProductNotFoundException( )
         {
         }

         public ProductNotFoundException( string message ) : base(message)
         {
         }

         public ProductNotFoundException( string message ,
                                          Exception inner ) : base(message, inner)
         {
         }

         protected ProductNotFoundException( SerializationInfo info ,
                                             StreamingContext context ) : base(info, context)
         {
         }

      }

      [Serializable()]
      public class ProductClassInvalidValue : Deklarit.UserException
      {
         public ProductClassInvalidValue( )
         {
         }

         public ProductClassInvalidValue( string message ) : base(message)
         {
         }

         public ProductClassInvalidValue( string message ,
                                          Exception inner ) : base(message, inner)
         {
         }

         protected ProductClassInvalidValue( SerializationInfo info ,
                                             StreamingContext context ) : base(info, context)
         {
         }

      }

      [Serializable()]
      public class ProductDataLockedException : Deklarit.DataLockedException
      {
         public ProductDataLockedException( )
         {
         }

         public ProductDataLockedException( string message ) : base(message)
         {
         }

         public ProductDataLockedException( string message ,
                                            Exception inner ) : base(message, inner)
         {
         }

         protected ProductDataLockedException( SerializationInfo info ,
                                               StreamingContext context ) : base(info, context)
         {
         }

      }

      [Serializable()]
      public class ProductDataChangedException : Deklarit.DataChangedException
      {
         public ProductDataChangedException( )
         {
         }

         public ProductDataChangedException( string message ) : base(message)
         {
         }

         public ProductDataChangedException( string message ,
                                             Exception inner ) : base(message, inner)
         {
         }

         protected ProductDataChangedException( SerializationInfo info ,
                                                StreamingContext context ) : base(info, context)
         {
         }

      }

      [Serializable()]
      public class InvoiceLineInvalidDeleteException : Deklarit.InvalidDeleteException
      {
         public InvoiceLineInvalidDeleteException( )
         {
         }

         public InvoiceLineInvalidDeleteException( string message ) : base(message)
         {
         }

         public InvoiceLineInvalidDeleteException( string message ,
                                                   Exception inner ) : base(message, inner)
         {
         }

         protected InvoiceLineInvalidDeleteException( SerializationInfo info ,
                                                      StreamingContext context ) : base(info, context)
         {
         }

      }


      protected void Cleanup( )
      {
         dsDefault.Dispose();
      }


      private void Initialize( )
      {
         resourceManager = Deklarit.Utils.ResourceManager.Instance ;
         resourceManagerTables = new System.Resources.ResourceManager( "Deklarit.Tables", System.Reflection.Assembly.GetExecutingAssembly()) ;
         scmdbuf = "" ;
         m__ProductNameOriginal = new object();
         m__ProductTypeOriginal = new object();
         m__ProductSizeOriginal = new object();
         m__ProductIsFragileOriginal = new object();
         m__ProductClassOriginal = new object();
         m_WhereString = "" ;
         if ( this.Transaction == null )
         {
            this.Transaction = ((System.Data.IDbTransaction)(System.Threading.Thread.GetData(System.Threading.Thread.GetNamedDataSlot(DeklaritTransaction.TransactionSlotName)) ));
         }
      }

      private short RcdFound4 ;
      private short IsModified ;
      private int recordCount ;
      private String scmdbuf ;
      private String m_WhereString ;
      private bool _Gxremove ;
      private DataStore dsDefault ;
      private System.Resources.ResourceManager resourceManager ;
      private System.Resources.ResourceManager resourceManagerTables ;
      private ReadWriteConnection connDefault ;
      private ReadWriteCommand cmPRODUCTSELECT1 ;
      private IDataReader PRODUCTSELECT1 ;
      private object m__ProductNameOriginal ;
      private object m__ProductTypeOriginal ;
      private object m__ProductSizeOriginal ;
      private object m__ProductIsFragileOriginal ;
      private object m__ProductClassOriginal ;
      private IDataReader PRODUCTSELECT3 ;
      private ReadWriteCommand cmPRODUCTSELECT4 ;
      private IDataReader PRODUCTSELECT4 ;
      private System.Data.StatementType Gx_mode ;
      private System.Data.StatementType sMode4 ;
   }

   public class ProductDataReader : System.IDisposable
   {
      public ProductDataReader( )
      {
      }

      private void init_reader( )
      {
         this.Initialize( ) ;
         dsDefault = new DataStore( new SqlServer2005Handler( ), "System.Data.SqlClient", DeklaritModel.Configuration.ConnectionString, DeklaritTransaction.TransactionSlotName) ;
         m_Disposed = false ;
         m_Closed = true ;
      }

      private IDbTransaction daCurrentTransaction ;
      ///  <summary>
      ///   Gets or sets the Transaction object to be used  by  ProductDataReaderDeklarit DataReaderclasses
      ///    to commit changes to the Database.
      ///  </summary>
      public IDbTransaction Transaction
      {
         get {
            return daCurrentTransaction ;
         }

         set {
            daCurrentTransaction = value ;
         }

      }

      public IDataReader Open( )
      {
         init_reader( ) ;
         m_Closed = false ;
         connDefault = dsDefault.GetReadWriteConnection( daCurrentTransaction) ;
         cmPRODUCTSELECT5 = connDefault.GetCommand("SELECT TM1.[ProductId], TM1.[ProductName], TM1.[ProductType], TM1.[ProductSize], TM1.[ProductIsFragile], TM1.[ProductClass] FROM [Product] TM1 ORDER BY TM1.[ProductId] ", false) ;
         PRODUCTSELECT5 = cmPRODUCTSELECT5.ExecuteReader(((daCurrentTransaction==null) ? Configuration.ReaderCommandBehavior : CommandBehavior.Default)) ;
         return PRODUCTSELECT5 ;
      }

      public IDataReader OpenByProductId( short productId )
      {
         init_reader( ) ;
         m_Closed = false ;
         connDefault = dsDefault.GetReadWriteConnection( daCurrentTransaction) ;
         cmPRODUCTSELECT5 = connDefault.GetCommand("SELECT TM1.[ProductId], TM1.[ProductName], TM1.[ProductType], TM1.[ProductSize], TM1.[ProductIsFragile], TM1.[ProductClass] FROM [Product] TM1 WHERE TM1.[ProductId] = @ProductId ORDER BY TM1.[ProductId] ", false) ;
         if ( cmPRODUCTSELECT5.IDbCommand.Parameters.Count == 0 )
         {
            cmPRODUCTSELECT5.IDbCommand.Parameters.Add(  dsDefault.GetDbParameter( "@ProductId", System.Data.DbType.Int16));
         }
         cmPRODUCTSELECT5.SetParameter(0, productId);
         PRODUCTSELECT5 = cmPRODUCTSELECT5.ExecuteReader(((daCurrentTransaction==null) ? Configuration.ReaderCommandBehavior : CommandBehavior.Default)) ;
         return PRODUCTSELECT5 ;
      }

      public void Dispose( )
      {
         if ( ! m_Disposed )
         {
            m_Disposed = true ;
            try
            {
               if ( ! m_Closed && ( PRODUCTSELECT5 != null ) )
               {
                  m_Closed = true ;
                  PRODUCTSELECT5.Close();
               }
            }
            finally
            {
               try
               {
                  connDefault.Close();
               }
               finally
               {
                  this.Cleanup();
               }
            }
         }
      }

      public void Close( )
      {
         this.Dispose( ) ;
      }


      protected void Cleanup( )
      {
         dsDefault.Dispose();
      }


      private void Initialize( )
      {
         scmdbuf = "" ;
         if ( this.Transaction == null )
         {
            this.Transaction = ((System.Data.IDbTransaction)(System.Threading.Thread.GetData(System.Threading.Thread.GetNamedDataSlot(DeklaritTransaction.TransactionSlotName)) ));
         }
      }

      private String scmdbuf ;
      private bool m_Disposed ;
      private bool m_Closed ;
      private DataStore dsDefault ;
      private ReadWriteConnection connDefault ;
      private ReadWriteCommand cmPRODUCTSELECT5 ;
      private IDataReader PRODUCTSELECT5 ;
   }

}
